let socket;
let heartInterval = 0;

/**
 * 创建socket
 * @param url
 * @param receiveMsg
 */
function create(url, receiveMsg) {
    socket = new WebSocket(url);
    socket.onclose = function () {
        reconnect(url,receiveMsg);
        console.log("连接关闭");
    };
    socket.onerror = function () {
        reconnect(url,receiveMsg);
        console.log("连接错误");
    };
    socket.onopen = function () {
        //heart();
        console.log("连接成功");
    };
    socket.onmessage = function (event) {
        receiveMsg(event);
    };
}

/**
 * 断线重连
 * @param url
 * @param receiveMsg
 */
function reconnect(url,receiveMsg) {
    if (reconnect.lockReconnect) return;
    reconnect.lockReconnect = true;
    setTimeout(function () {
        create(url,receiveMsg);
        reconnect.lockReconnect = false;
    }, 2000);
}

/**
 * 心跳
 */
function heart() {
    setInterval(function () {
        heartInterval++;
        if (heartInterval === 10) {
            sendMsg(JSON.stringify({
                url: "192.168.2.40",
                port: "8005",
                code: 2
            }));
        }
    }, 1000);
}

/**
 * 重置心跳间隔
 */
function reset() {
    heartInterval = 0;
}

/**
 * 发送消息
 * @param msg
 */
function sendMsg(msg) {
    console.log("发送的消息=",msg);
    if (socket.readyState === WebSocket.OPEN) {
        socket.send(msg);
        reset();
    }
}